package com.example.filesharing.handler;

import com.example.filesharing.utils.FileUtils;
import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.RequestMethod;
import com.yanzhenjie.andserver.annotation.RequestMapping;
import com.yanzhenjie.andserver.util.HttpRequestParser;

import org.apache.httpcore.HttpException;
import org.apache.httpcore.HttpRequest;
import org.apache.httpcore.HttpResponse;
import org.apache.httpcore.entity.StringEntity;
import org.apache.httpcore.protocol.HttpContext;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

public class FileDeleteHandler implements RequestHandler {
    @RequestMapping(method={RequestMethod.POST})
    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        String contentFromBody = HttpRequestParser.getContentFromBody(request);//从请求体中获取数据
        System.out.println("请求体："+contentFromBody);
        String substring = contentFromBody.substring(5, contentFromBody.length());
        String decode= URLDecoder.decode(substring, "utf-8");
        File file = new File(FileUtils.fileDirectory + "/" + decode);
        boolean delete = file.delete();
        String s="";
        if(delete){
            s="删除文件“"+decode+"”成功！";
        }else{
            s="删除文件“"+decode+"”失败！";
        }

        StringEntity entity=new StringEntity(s,"utf-8");
        response.setEntity(entity);
        response.setHeader("Content-Type","text/html;chartset=utf-8");

    }
}
